<template>
  <div>
    <main-layout>
      <template v-slot:top>
        <el-form ref="searchForm" :inline="true" :model="searchInfo">
          <el-form-item label="用户ID">
            <el-input v-model="searchInfo.miguUid" placeholder="用户ID" clearable />
          </el-form-item>
          <el-form-item label="手机号码">
            <el-input v-model="searchInfo.phone" placeholder="手机号码" clearable />
          </el-form-item>
          <el-form-item label="角色性别">
            <el-select v-model="searchInfo.sex" clearable placeholder="请选择" style="width: 140px;">
              <el-option :value="1" label="男" />
              <el-option :value="2" label="女" />
            </el-select>
          </el-form-item>
          <el-form-item label="注册时间">
            <el-date-picker v-model="time" type="datetimerange" range-separator="至" start-placeholder="开始时间"
              end-placeholder="结束时间" value-format="YYYY-MM-DD HH:mm:ss"/>
          </el-form-item>

          <el-form-item>
            <el-button size="small" type="primary" icon="search" @click="onSubmit">查询</el-button>
            <el-button size="small" icon="refresh" @click="onReset">重置</el-button>
          </el-form-item>
        </el-form>
      </template>

      <div class="gva-btn-list">
        <!-- <el-button size="small" type="primary" icon="download" @click="exportExcel">导出</el-button> -->
        <popover-botton text="导出" icon="download" :lists="[{id:1,label:'全部导出'},{id:2,label:'导出选中数据'}]" @itemClick="exportExcel"/>
      </div>

      <c-table ref="tableRef" :page="{ pageSize, pageIndex, total }" :lists="tableData" @current-change="handleCurrentChange"
        @size-change="handleSizeChange" :loading="loading" showCheck @selection-change="selectionChange" rowKey="_id">
        <el-table-column align="center" label="昵称" min-width="150" prop="nickname" />
        <el-table-column align="center" label="手机号" min-width="110" prop="phone" >
          <template #default="scope">
            {{ phoneReplace(scope.row.phone) }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="账号余额" min-width="120" prop="balance"></el-table-column>
        <el-table-column align="center" label="专属邀请码" min-width="120" prop="selfInviteCode" />
        <el-table-column align="center" label="注册时间" width="180" >
          <template #default="scope">
            {{ formatDateLong(scope.row.createTime) }}
          </template>
        </el-table-column>
      </c-table>

    </main-layout>

  </div>
</template>

<script setup name="userList">
import { nextTick, ref, watch, onActivated,reactive,onMounted } from 'vue'
import {getUserList} from '@/api/user'

import mainLayout from '@/components/custom/mainLayout.vue'
import cTable from '@/components/custom/cTable.vue'
import popoverBotton from '@/components/custom/popoverBotton.vue'

import {formatDateLong,phoneReplace,formatDate} from '@/utils/format'

import { useUserStore } from '@/pinia/modules/user'
import {exportToExcel} from '@/utils/exportExcel'
import {message} from '@/utils/element'

const userStore = useUserStore()


onMounted(()=>{
  init()
})

const pageIndex = ref(1)
const total = ref(0)
const pageSize = ref(10)
const tableData = ref([])
const searchInfo = ref({})
const time = ref('')
const loading = ref(true)
const tableRef = ref(null)


const init = () => {
  pageIndex.value = 1
  onReset()
  getTableData()
}

const onReset = () => {
  time.value = ''
  searchInfo.value = {}
}
// 搜索
const onSubmit = () => {
  pageIndex.value = 1
  tableRef.value.clear_selection()  // 清空所选
  getTableData()
}
// 分页
const handleSizeChange = (val) => {
  pageIndex.value = 1
  pageSize.value = val
  getTableData()
}

const handleCurrentChange = (val) => {
  pageIndex.value = val
  getTableData()
}

// 查询
const getTableData = async () => {
  if(time.value){
    searchInfo.value.createTimeStart = time.value[0]
    searchInfo.value.createTimeEnd = time.value[1]
  }else{
        delete searchInfo.value.createTimeStart
        delete searchInfo.value.createTimeEnd
  }
  const res = await getUserList({ page: pageIndex.value, size: pageSize.value, ...searchInfo.value })
  if (res.code === 200) {
    tableData.value = res.data
    total.value = res.total
  }
  loading.value = false
}

let tableCheckeds = []
const selectionChange= (items)=>{
  tableCheckeds = items
}

const exportExcel = async (o)=>{
  //console.log('tableCheckeds',tableCheckeds)
  if(o.id == 2){
    if(!tableCheckeds.length){
      return message('请选择需要导出的数据',3)
    }
  }else{
    console.log("全部导出")
    const res = await getUserList({ page: 1, size: 1000})
    if (res.code === 200) {
      tableCheckeds = res.data
    }else{
      return message('获取数据出错了，请重试',3)
    }
  }

  const headers = ["序号", '用户ID', '手机号', "角色性别", "当前球服", "当前绿色能量数", "绿色能量总获取数", "注册时间"]
  let lists =[] //[[1,'1985-02-15','tom1','地址1'],[2,'2001-05-20','tom2','地址2']]
  tableCheckeds.forEach((item, index) =>{
    const arr = [
      index + 1,
      item.userId,
      item.phone,
      item.sex==1?'男':(item.sex==2?'女':''),
      item.dressType,
      item.greenEnergyAmount,
      item.greenEnergyAmountTotal,
      formatDateLong(item.createTime)
    ]
    lists.push(arr)
  })
  const fileName = `${formatDate(new Date())}用户信息管理`.replace(/-/g,"")

  exportToExcel(fileName,headers,lists)
}


</script>

<style lang="scss" scoped>
.inputLine {
  display: flex;
  width: 300px;
  .zhi{
    padding: 0 10px;
  }
  s{
    font-style: normal;
    text-decoration: none;
    padding: 0 0 0 5px;
    color: var(--el-text-color-regular);
  }
}
</style>
